<template>
  <base-layout @tenant-change="changeTenant" simple>
    <article class="base-layout__inner column">
      <!-- 疾病分类选择 -->
      <div class="disease-category-selector">
        <t-select
          v-model="selectedDiseaseCategory"
          placeholder="请选择疾病分类"
          :loading="diseaseCategoryLoading"
          @change="handleDiseaseCategoryChange"
          style="width: 300px;"
        >
          <t-option
            v-for="category in diseaseCategoryList"
            :key="category.id"
            :value="category.id"
            :label="category.name"
          >
            {{ category.name }}
          </t-option>
        </t-select>
      </div>

      <!-- 目录结构 -->
      <div class="catalog-tree-container">
        <div class="catalog-tree-header">
          <h3>目录结构</h3>
          <t-button theme="primary" @click="handleAddRootNode">
            <template #icon><t-icon name="add" /></template>
            添加根目录
          </t-button>
        </div>

        <t-tree
          ref="catalogTree"
          :data="treeData"
          :keys="treeKeys"
          :expand-all="false"
          :expand-level="1"
          :allow-drop="allowDrop"
          :allow-drag="allowDrag"
          :loading="treeLoading"
          :draggable="false"
          @drop="handleDrop"
          class="catalog-tree"
        >
          <template #label="{ node }">
            <div class="tree-node-content">
              <div class="node-info">
                <span class="node-name">{{ node.data.name }}</span>
                <span class="node-time" v-if="node.data.pushStartTime">
                  推送时间: {{ formatTime(node.data.pushStartTime) }} - {{ formatTime(node.data.pushEndTime) }}
                </span>
              </div>
              <div class="node-actions" @click.stop>
                <t-button
                  theme="primary"
                  variant="text"
                  size="small"
                  @click="handleAddChild(node)"
                  title="添加子节点"
                >
                  添加
                </t-button>
                <t-button
                  theme="primary"
                  variant="text"
                  size="small"
                  @click="handleEditNode(node)"
                  title="编辑目录"
                >
									编辑目录
                </t-button>
                <t-button
                  theme="primary"
                  variant="text"
                  size="small"
                  @click="handleEditContent(node)"
                  title="编辑内容"
                >
                  编辑内容
                </t-button>
                <t-button
                  theme="danger"
                  variant="text"
                  size="small"
                  @click="handleDeleteNode(node)"
                  title="删除"
                  class="delete-btn"
                  v-if="canDeleteNode(node)"
                >
                  删除
                </t-button>
              </div>
            </div>
          </template>
        </t-tree>

        <!-- 空状态提示 -->
        <div v-if="!treeLoading && treeData.length === 0" class="empty-state">
          <t-icon name="folder" size="48px" class="empty-icon" />
          <p class="empty-text">暂无目录数据</p>
          <p class="empty-desc" v-if="!selectedDiseaseCategory">请先选择疾病分类</p>
          <p class="empty-desc" v-else>点击上方"添加根目录"按钮开始创建目录结构</p>
        </div>
      </div>
    </article>

    <!-- 目录编辑表单 -->
    <catalog-form
      v-model="catalogFormVisible"
      :node-data="currentEditNode"
      :parent-node="currentParentNode"
      :category-id="Number(selectedDiseaseCategory)"
      @success="handleCatalogFormSuccess"
    />

    <!-- 内容编辑抽屉 -->
    <content-drawer
      v-model="contentDrawerVisible"
      :node-data="currentContentNode"
      :category-id="selectedDiseaseCategory"
      @success="handleContentDrawerSuccess"
    />
  </base-layout>
</template>

<script>
import BaseLayout from '@/components/base-layout/index.vue';
import CatalogForm from './catalog-form.vue';
import ContentDrawer from './content-drawer.vue';
import { mapGetters } from 'vuex';
import { getDiseaseList } from '@/api/disease';
import { getCatalogTree, addCatalogNode, updateCatalogNode, deleteCatalogNode, updateNodePosition } from '@/api/catalog';
import { DialogPlugin as TDialog } from 'tdesign-vue';

export default {
  name: 'OperationKnowledgeCatalog',
  components: {
    BaseLayout,
    CatalogForm,
    ContentDrawer,
  },
  data() {
    return {
      diseaseCategoryLoading: false,
      // 疾病分类相关
      diseaseCategoryList: [],
      selectedDiseaseCategory: null,

      // 树形结构相关
      treeData: [],
      treeLoading: false,
      treeKeys: {
        value: 'id',
        label: 'name',
        children: 'children',
      },

      // 目录编辑表单相关
      catalogFormVisible: false,
      currentEditNode: null,
      currentParentNode: null,

      // 内容编辑抽屉相关
      contentDrawerVisible: false,
      currentContentNode: null,
    };
  },
  computed: {
    ...mapGetters({
      tenantId: 'user/tenantId',
      isSuperAdmin: 'user/isSuperAdmin',
    }),
  },
  mounted() {
    this.loadDiseaseCategoryList();
  },
  methods: {
    // 加载疾病分类列表
    async loadDiseaseCategoryList() {
      this.diseaseCategoryLoading = true;
      try {
        const res = await getDiseaseList();
        this.diseaseCategoryList = res?.data?.data || [];

        // 默认选择第一个分类
        if (this.diseaseCategoryList.length > 0) {
          this.selectedDiseaseCategory = this.diseaseCategoryList[0].id;
          // 加载默认分类的目录树
          await this.loadCatalogTree();
        }
      } catch (error) {
        console.error('加载疾病分类失败:', error);
        this.$message.error('加载疾病分类失败');
        this.diseaseCategoryList = [];
      } finally {
        this.diseaseCategoryLoading = false;
      }
    },

    // 疾病分类变化处理
    async handleDiseaseCategoryChange(categoryId) {
      this.selectedDiseaseCategory = categoryId;
      await this.loadCatalogTree();
    },

    // 加载目录树数据
    async loadCatalogTree() {
      if (!this.selectedDiseaseCategory) {
        this.treeData = [];
        return;
      }

      this.treeLoading = true;
      try {
        const res = await getCatalogTree(this.selectedDiseaseCategory);

        if (res?.data?.code === 200) {
          this.treeData = res.data.data || [];
        } else {
          throw new Error(res?.data?.message || '获取目录树失败');
        }
      } catch (error) {
        console.error('加载目录树失败:', error);
        this.$message.error(error.message || '加载目录树失败');
        this.treeData = [];
      } finally {
        this.treeLoading = false;
      }
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '';
      return new Date(time).toLocaleString('zh-CN');
    },

    // 允许拖拽
    allowDrag(node) {
      return true;
    },

    // 允许放置
    allowDrop(dragNode, dropNode, position) {
      return true;
    },

    // 处理拖拽放置
    async handleDrop(context) {
      try {
        const { dragNode, dropNode, position } = context;

        // 构建位置更新数据
        const positionData = {
          dragNodeId: dragNode.data.id,
          dropNodeId: dropNode.data.id,
          position: position, // 'before', 'after', 'inner'
          categoryId: this.selectedDiseaseCategory
        };

        const res = await updateNodePosition(positionData);

        if (res?.data?.code === 200) {
          this.$message.success('节点位置已更新');
          // 重新加载树数据以确保数据一致性
          await this.loadCatalogTree();
        } else {
          throw new Error(res?.data?.message || '更新节点位置失败');
        }
      } catch (error) {
        console.error('拖拽更新失败:', error);
        this.$message.error(error.message || '更新节点位置失败');
        // 重新加载树数据以恢复原始状态
        await this.loadCatalogTree();
      }
    },

    // 添加根节点
    handleAddRootNode() {
      if (!this.selectedDiseaseCategory) {
        this.$message.warning('请先选择疾病分类');
        return;
      }

      // 创建新的节点数据结构，没有 id 表示新增
      this.currentEditNode = {
        code: '',
        name: '',
        pushStartTime: '',
        pushEndTime: '',
        description: '',
        // 没有 id，表示这是新增操作
      };
      this.currentParentNode = null;
      this.catalogFormVisible = true;
    },

    // 添加子节点
    handleAddChild(node) {
      // 创建新的节点数据结构，没有 id 表示新增
      this.currentEditNode = {
        code: '',
        name: '',
        pushStartTime: '',
        pushEndTime: '',
        description: '',
        // 没有 id，表示这是新增操作
      };
      this.currentParentNode = node;
      this.catalogFormVisible = true;
    },

    // 编辑节点
    handleEditNode(node) {
      // 使用现有节点数据，有 id 表示编辑
      this.currentEditNode = {
        id: node.data.id,
        code: node.data.code || '',
        name: node.data.name || '',
        pushStartTime: node.data.pushStartTime || '',
        pushEndTime: node.data.pushEndTime || '',
        description: node.data.description || '',
      };
      this.currentParentNode = null;
      this.catalogFormVisible = true;
    },

    // 编辑内容
    handleEditContent(node) {
      this.currentContentNode = node.data;
      this.contentDrawerVisible = true;
    },

    // 删除节点
    async handleDeleteNode(node) {
      // 基本验证
      if (!node || !node.data || !node.data.id) {
        this.$message.error('无效的节点数据');
        return;
      }

      // 检查节点是否正在推送中
      const now = new Date();
      const pushStartTime = node.data.pushStartTime ? new Date(node.data.pushStartTime) : null;
      const pushEndTime = node.data.pushEndTime ? new Date(node.data.pushEndTime) : null;

      if (pushStartTime && pushEndTime && now >= pushStartTime && now <= pushEndTime) {
        this.$message.warning('该节点正在推送期间，无法删除');
        return;
      }

      // 递归计算所有子节点数量
      const countAllChildren = (nodeData) => {
        let count = 0;
        if (nodeData.children && nodeData.children.length > 0) {
          count += nodeData.children.length;
          nodeData.children.forEach(child => {
            count += countAllChildren(child);
          });
        }
        return count;
      };

      const totalChildrenCount = countAllChildren(node);
      const hasChildren = totalChildrenCount > 0;

      let confirmMessage = '';
      let warningMessage = '';

      if (hasChildren) {
        confirmMessage = `节点"${node.data.name}"包含 ${totalChildrenCount} 个子节点，删除后所有子节点也将被删除。`;
        warningMessage = '此操作不可恢复，请谨慎操作！';
      } else {
        confirmMessage = `确定要删除节点"${node.data.name}"吗？`;
        warningMessage = '删除后不可恢复。';
      }

      try {
        // 使用TDesign推荐的确认对话框
        const confirmDialog = await new Promise((resolve) => {
          const instance = TDialog.confirm({
            header: '确认删除',
            body: () => {
              return this.$createElement('div', {
                style: {
                  lineHeight: '1.6'
                }
              }, [
                this.$createElement('p', {
                  style: {
                    margin: '0 0 8px 0',
                    color: '#333'
                  }
                }, confirmMessage),
                this.$createElement('p', {
                  style: {
                    margin: '0',
                    color: '#ff4d4f',
                    fontWeight: '500'
                  }
                }, warningMessage)
              ]);
            },
            confirmBtn: {
              content: hasChildren ? '确定删除全部' : '确定删除',
              theme: 'danger',
              loading: false
            },
            cancelBtn: '取消',
            onConfirm: () => {
              resolve(instance);
            },
            onCancel: () => {
              resolve(null);
            },
          });
        });

        // 用户取消删除
        if (!confirmDialog) {
          return;
        }

        // 显示删除按钮加载状态
        confirmDialog.update({
          confirmBtn: {
            content: '删除中...',
            theme: 'danger',
            loading: true
          }
        });

        // 调用删除API
        const res = await deleteCatalogNode(node.data.id);

        if (res?.data?.code === 200) {
          confirmDialog.hide();
          const successMessage = hasChildren
            ? `成功删除节点"${node.data.name}"及其 ${totalChildrenCount} 个子节点`
            : `成功删除节点"${node.data.name}"`;
          this.$message.success(successMessage);
          // 重新加载树数据
          await this.loadCatalogTree();
        } else {
          throw new Error(res?.data?.message || '删除失败');
        }
      } catch (error) {
        console.error('删除节点失败:', error);

        // 根据错误类型显示不同的错误信息
        let errorMessage = '删除失败';
        if (error.message) {
          errorMessage = error.message;
        } else if (error.response?.data?.message) {
          errorMessage = error.response.data.message;
        } else if (error.response?.status === 403) {
          errorMessage = '没有权限删除此节点';
        } else if (error.response?.status === 409) {
          errorMessage = '该节点正在被使用，无法删除';
        } else if (error.code === 'NETWORK_ERROR') {
          errorMessage = '网络连接失败，请检查网络后重试';
        }

        this.$message.error(errorMessage);

        // 如果对话框还存在，隐藏它
        if (confirmDialog) {
          confirmDialog.hide();
        }
      }
    },

    // 处理目录编辑表单成功
    handleCatalogFormSuccess() {
      // 重新加载树数据
      this.loadCatalogTree();
    },

    // 处理内容编辑抽屉成功
    handleContentDrawerSuccess() {
      // 重新加载树数据
      this.loadCatalogTree();
    },

    // 租户变化
    changeTenant(tenant) {
      // 租户变化时的处理逻辑
      this.loadCatalogTree();
    },

    // 检查是否可以删除节点
    canDeleteNode(node) {
      // 基本验证
      if (!node || !node.data) {
        return false;
      }

      // 超级管理员可以删除任何节点
      if (this.isSuperAdmin) {
        return true;
      }

      // 检查节点是否处于可删除状态
      // 例如：如果节点正在推送中，则不能删除
      const now = new Date();
      const pushStartTime = node.data.pushStartTime ? new Date(node.data.pushStartTime) : null;
      const pushEndTime = node.data.pushEndTime ? new Date(node.data.pushEndTime) : null;

      // 如果节点正在推送期间，不允许删除
      if (pushStartTime && pushEndTime && now >= pushStartTime && now <= pushEndTime) {
        return false;
      }

      // 其他权限检查逻辑可以在这里添加
      // 例如：检查用户是否是节点的创建者，或者是否有相应的权限

      return true;
    },
  },
};
</script>

<style lang="less" scoped>
.disease-category-selector {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e7e7e7;

  &::before {
    content: '疾病分类：';
    margin-right: 8px;
    font-weight: 500;
    color: #333;
  }
}

.catalog-tree-container {
  flex: 1;
  background-color: #fff;
  border-radius: 6px;
  border: 1px solid #e7e7e7;
  overflow: hidden;

  .catalog-tree-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #e7e7e7;
    background-color: #fafafa;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
      color: #333;
    }
  }

  .catalog-tree {
    padding: 16px;
    max-height: calc(100vh - 300px);
    overflow-y: auto;

    :deep(.t-tree-node) {
      margin-bottom: 8px;

      .t-tree-node__content {
        padding: 8px 12px;
        border-radius: 4px;
        transition: all 0.2s;

        &:hover {
          background-color: #f0f8ff;
        }
      }

      &.t-tree-node--selected .t-tree-node__content {
        background-color: #e6f4ff;
        border-color: #1890ff;
      }
    }
  }
}

.tree-node-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  min-height: 32px;
  padding: 4px 8px;
  border-radius: 4px;
  transition: background-color 0.2s ease;

  .node-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 4px;

    .node-name {
      font-size: 14px;
      font-weight: 500;
      color: #333;
      line-height: 1.4;
      transition: color 0.2s ease;
    }

    .node-time {
      font-size: 12px;
      color: #999;
      line-height: 1.2;
    }
  }

  .node-actions {
    display: flex;
    gap: 4px;
    opacity: 0;
    transition: opacity 0.2s;

    .delete-btn {
      &:hover {
        background-color: #fff2f0;
        border-color: #ff7875;
        color: #ff4d4f;
      }
    }
  }

  &:hover {
    background-color: #f7f7f7;

    .node-info .node-name {
      color: var(--td-brand-color, #0052d9);
    }

    .node-actions {
      opacity: 1;
    }
  }
}

// 对话框样式优化
:deep(.t-dialog__body) {
  padding: 20px 24px;
}

:deep(.t-form-item__label) {
  font-weight: 500;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
  min-height: 200px;

  .empty-icon {
    margin-bottom: 16px;
    color: #ddd;
  }

  .empty-text {
    margin: 0 0 8px 0;
    font-size: 16px;
    font-weight: 500;
    color: #666;
  }

  .empty-desc {
    margin: 0;
    font-size: 14px;
    color: #999;
    line-height: 1.5;
  }
}
</style>
